<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row class="ml10" v-show="showSearch">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="姓名" prop="cusName">
						<el-input placeholder="请输入姓名" style="max-width: 180px" v-model="state.queryForm.cusName" />
					</el-form-item>
          <el-form-item label="手机号" prop="cusTel">
            <el-input placeholder="请输入手机号" style="max-width: 180px" v-model="state.queryForm.cusTel" />
          </el-form-item>
          <el-form-item label="订单号" prop="orderNumber">
            <el-input placeholder="请输入订单号" style="max-width: 180px" v-model="state.queryForm.orderNumber" />
          </el-form-item>
          <el-form-item label="行程单号" prop="tripNumber">
            <el-input placeholder="请输入行程单号" style="max-width: 180px" v-model="state.queryForm.tripNumber" />
          </el-form-item>
					<el-form-item>
						<el-button @click="getDataList" icon="search" type="primary">
							查询
						</el-button>
						<el-button @click="resetQuery" icon="Refresh">重置</el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-table
				:data="state.dataList"
				@selection-change="handleSelectionChange"
				style="width: 100%"
				v-loading="state.loading"
				border
				:cell-style="tableStyle?.cellStyle"
				:header-cell-style="tableStyle?.headerCellStyle"
			>
				<el-table-column align="center" type="selection" width="40" />
				<el-table-column label="序号" type="index" width="60" />
				<el-table-column label="订单号" prop="orderNumber" show-overflow-tooltip />
        <el-table-column label="行程单号" prop="tripNumber" show-overflow-tooltip >
          <template #default="scope">
            <span style="color: blue; text-decoration: underline; cursor: pointer;" @click="handleTripNumberClick(scope.row.tripNumber)">{{ scope.row.tripNumber }}</span>
          </template>
        </el-table-column>

				<el-table-column label="客户姓名" prop="cusName" show-overflow-tooltip />
				<el-table-column label="地陪" prop="guideId" show-overflow-tooltip />
        <el-table-column label="定制师" prop="tailotrId" show-overflow-tooltip />
        <el-table-column label="订单金额" prop="orderAmount" show-overflow-tooltip />
        <el-table-column label="手机号" prop="cusTel" show-overflow-tooltip />
        <el-table-column label="状态" prop="orStatus" show-overflow-tooltip >
          <template #default="scope">
            <dict-tag :options="startTypeDict" :value="scope.row.orStatus"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <!-- 状态为“未开始”：显示【开始】和【跟进】按钮 -->
            <template v-if="scope.row.orStatus === '0'">
              <el-button
                  @click="handleStart(scope.row)"
                  text
                  type="primary"
                  style="margin-right: 5px"
              >
                开始
              </el-button>
              <el-button
                  @click="handleFollow(scope.row.orderId)"
                  text
                  type="success"
              >
                跟进
              </el-button>

            </template>

            <!-- 状态为“进行中”：显示【跟进】和【结束】按钮 -->
            <template v-else-if="scope.row.orStatus === '1'">
              <el-button
                  @click="handleFollow(scope.row.orderId)"
                  text
                  type="success"
                  style="margin-right: 5px"
              >
                跟进
              </el-button>
              <el-button
                  @click="handleEnd(scope.row)"
                  text
                  type="warning"
              >
                结束
              </el-button>
            </template>

            <!--  状态为“已结束”：只显示【跟进】按钮 -->
            <template v-else-if="scope.row.orStatus === '2'">
              <el-button
                  @click="handleFollow(scope.row.orderId)"
                  text
                  type="success"
              >
                跟进
              </el-button>
            </template>
          </template>
        </el-table-column>
			</el-table>


      <!-- 跟进弹窗（复用之前的弹窗，新增结束按钮逻辑） -->
      <el-dialog
          title="订单跟进"
          v-model="followDialogVisible"
          width="500px"
          :close-on-click-modal="false"
      >
        <el-form-item label="跟进备注" prop="remark">
          <el-input
              v-model="followForm.remark"
              type="textarea"
              rows="4"
              placeholder="请输入跟进内容..."
          />
        </el-form-item>
        <template #footer>
          <el-button @click="followDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitFollow">确认提交</el-button>
        </template>
      </el-dialog>

      <!-- 添加分页组件 -->
      <el-pagination
          :current-page="state.pagination?.current"
          :page-sizes="state.pagination?.pageSizes"
          :page-size="state.pagination?.size"
          :total="state.pagination?.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle" style="margin-top: 20px; text-align: center"
      />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog @refresh="getDataList()" ref="formDialogRef" />
	</div>
</template>

<script lang="ts" name="systemPost" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { page,updateStutas} from '/@/api/order/order';
import { useMessage} from '/@/hooks/message';
import { ElMessageBox } from 'element-plus';
import { useDict } from '/@/hooks/dict';
import { useRouter } from 'vue-router';
//路由跳转
const router = useRouter();
// 点击行程单号跳转方法
const handleTripNumberClick = (tripNumber: string) => {
  router.push({
    path: '/trip/index',
    params: { tripNumber }
  });
};

const handleFollow = (orderId:number) => {
  // 跳转到跟进页面，传递订单ID
  router.push({
    path:'/follow',
    name: 'follow', params: { orderId } });
};
const { start_type } = useDict('start_type')
const startTypeDict = start_type;



// 定义变量内容
const formDialogRef = ref();

// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);

//状态和变量定义
const message = useMessage();
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {},
	pageList: page,//表格数据
});

// 跟进弹窗相关
const followDialogVisible = ref(false);
const followForm = reactive({
  orderId: '',
  remark: '',
  orStatus: '' // 用于暂存当前状态（区分是普通跟进还是结束操作）
});

//  table hook
const { getDataList,tableStyle,sizeChangeHandle,currentChangeHandle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	queryRef.value.resetFields();
	getDataList();
};

// 多选事件
const handleSelectionChange = (objs: { postId: string }[]) => {
	selectObjs.value = objs.map(({ postId }) => postId);
	multiple.value = !objs.length;
};

// 开始按钮点击事件；未开始  进行中
const handleStart = async (row: any) => {
  try {
    const params = {
      orderId: row.orderId ,
      orStatus: '1',
      remark: '订单开始执行'
    };
    const res = await updateStutas(params);
    if(res.code === 0){
      useMessage().success("状态已更新进行中");
      getDataList();
    }else{
      useMessage().error(res.msg || '操作失败')
    }
  } catch (err: any) {
    useMessage().error('操作失败，请重试');
  }
};
//结束按钮， 进行中  已结束
const handleEnd = async (row: any) =>{
  // 二次确认，避免误操作
  const confirm = await ElMessageBox.confirm(
      '确定要结束该订单吗？结束后状态将变为“已结束”',
      '确认结束',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).catch(() => false);

  if (!confirm) return;

  try {
    const res = await updateStutas({
      orderId: row.orderId ,
      orStatus: '2', // 状态变更为“已结束”
      remark: '订单结束执行' // 自动添加操作备注
    });
    if (res.code === 0) {
      message.success('订单已结束，状态更新为“已结束”');
      // 刷新表格，按钮会切换为“跟进”
      getDataList();
    } else {
      message.error(res.msg || '结束操作失败');
    }
  } catch (err) {
    message.error('操作失败，请重试');
  }
}

// 提交跟进备注（支持所有状态下的跟进）
const submitFollow = async () => {
  if (!followForm.remark.trim()) {
    useMessage().wraning('请输入跟进备注');
    return;
  }
  try {
    const res = await updateStutas({
      orderId: followForm.orderId ,
      orStatus: followForm.orStatus, // 保持当前状态（不改变状态，仅添加备注）
      remark: followForm.remark
    });
    if (res.code === 0) {
      message.success('跟进成功');
      followDialogVisible.value = false;
      getDataList();
    } else {
      message.error(res.msg || '跟进失败');
    }
  } catch (err) {
    message.error('跟进操作失败');
  }
};
</script>
